package org.dromara.system.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.system.domain.*;
import org.dromara.system.domain.bo.WbCompanyProductListBo;
import org.dromara.system.domain.bo.WbItemFileBo;
import org.dromara.system.mapper.WbCompanyInfoMapper;
import org.dromara.system.mapper.WbCompanyProductListMapper;
import org.dromara.system.mapper.WbItemFileMapper;
import org.dromara.system.utils.ExcelPlusUtil;
import org.dromara.system.utils.ImportExcelUtil;
import org.dromara.system.utils.MaxExcelUtil;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.WbProductPatentBo;
import org.dromara.system.domain.vo.WbProductPatentVo;
import org.dromara.system.mapper.WbProductPatentMapper;
import org.dromara.system.service.IWbProductPatentService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 产品专利Service业务层处理
 *
 * @author Lion Li
 * @date 2024-03-25
 */
@RequiredArgsConstructor
@Service
public class WbProductPatentServiceImpl implements IWbProductPatentService {

    private final WbProductPatentMapper baseMapper;

    private final WbCompanyProductListMapper wbCompanyProductListMapper;

    private final WbCompanyInfoMapper wbCompanyInfoMapper;

    /**
     * 查询产品专利
     */
    @Override
    public WbProductPatentVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询产品专利列表
     */
    @Override
    public TableDataInfo<WbProductPatentVo> queryPageList(WbProductPatentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WbProductPatent> lqw = buildQueryWrapper(bo);
        Page<WbProductPatentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询产品专利列表
     */
    @Override
    public List<WbProductPatentVo> queryList(WbProductPatentBo bo) {
        LambdaQueryWrapper<WbProductPatent> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<WbProductPatent> buildQueryWrapper(WbProductPatentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WbProductPatent> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCompanyId() != null, WbProductPatent::getCompanyId, bo.getCompanyId());
        lqw.like(StringUtils.isNotBlank(bo.getPatentName()), WbProductPatent::getPatentName, bo.getPatentName());
        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), WbProductPatent::getCompanyName, bo.getCompanyName());
        lqw.eq(StringUtils.isNotBlank(bo.getPatentee()), WbProductPatent::getPatentee, bo.getPatentee());
        lqw.eq(bo.getLicensingNoticeTime() != null, WbProductPatent::getLicensingNoticeTime, bo.getLicensingNoticeTime());
        lqw.orderByDesc(WbProductPatent::getId);
        return lqw;
    }

    /**
     * 新增产品专利
     */
    @Override
    public Boolean insertByBo(WbProductPatentBo bo) {
        WbProductPatent add = MapstructUtils.convert(bo, WbProductPatent.class);
        validEntityBeforeSave(add);
        Long companyId = add.getCompanyId();
        String companyName=baseMapper.getCompanyName(companyId);
        add.setCompanyName(companyName);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改产品专利
     */
    @Override
    public Boolean updateByBo(WbProductPatentBo bo) {
        WbProductPatent update = MapstructUtils.convert(bo, WbProductPatent.class);
        validEntityBeforeSave(update);
        Long companyId = update.getCompanyId();
        String companyName=baseMapper.getCompanyName(companyId);
        update.setCompanyName(companyName);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(WbProductPatent entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除产品专利
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String verify(MultipartFile file) throws Exception {
        String date="";

            //验证文件类型
            //获取数据
            List<List<Object>> olist = MaxExcelUtil.getListOfDoubleTableSheet(file.getInputStream(), file.getOriginalFilename(), "产品业绩", "供货业绩");
            int sum = 0;
            int num=0;
            for (List<Object> objects : olist) {
                String s = String.valueOf(objects.get(6));
                if (!Objects.equals(s, "-") || !s.equals("/")){
                    num=0;
                }
                else {
                    num = Integer.parseInt(String.valueOf(objects.get(6)));
                }
                //封装公司信息数据
                sum = sum + num;
            }
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(0, originalFilename.lastIndexOf("."));
            String temp[] = substring.split("_");
            String companyName = temp[0];
            String fileNameCC = temp[1];
            String[] fileNameAll = fileNameCC.split("核");
            String productName = fileNameAll[0];
            WbCompanyProductList wbCompanyProductList=baseMapper.findCompanyProduct(productName,companyName);
            WbCompanyProductList bo = new WbCompanyProductList();
            if (wbCompanyProductList!=null){
                WbProductInfo wbProductInfo = baseMapper.verify(sum, productName);
                if (wbProductInfo != null) {
                    bo.setStatus("2");
                    baseMapper.updateStatus(companyName,bo);
                    date="预审通过";
                }else {
                    bo.setStatus("3");
                    baseMapper.updateStatus(companyName,bo);
                    date="预审不通过";
                }
            }else {
                Long l = wbCompanyInfoMapper.selectId(companyName);
                if (l!=null){
                    bo.setCompanyId(String.valueOf(l));
                }
                bo.setCompanyId(String.valueOf(l));
                bo.setCompanyName(companyName);
                bo.setProductName(productName);
                WbProductInfo wbProductInfo = baseMapper.verify(sum, productName);
                if (wbProductInfo != null) {
                    bo.setStatus("2");
                    wbCompanyProductListMapper.insert(bo);
                    date="预审通过";
                }else {
                    bo.setStatus("3");
                    wbCompanyProductListMapper.insert(bo);
                    date="预审不通过";
                }
            }

        return date;
    }

}
